/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-11-27     RT-Thread    first version
 */

#include <rtthread.h>
#include "main.h"
#include "drv_common.h"
#include "Timer_APP.h"
#include "water_quality.h" 


#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>
#define PRINTF_BUF_SIZE 100
#define RECEIVELEN 1152
#define USART_DMA_SENDING 1
#define USART_DMA_SENDOVER 0


typedef struct
{
    rt_uint8_t receive_flag : 1;
    rt_uint8_t dmaSend_flag : 1;
    rt_uint16_t rx_len;
    rt_uint8_t usartDMA_rxBuf[RECEIVELEN];
} USART_RECEIVETYPE;


ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
UART_HandleTypeDef huart2; //wifi����
UART_HandleTypeDef huart3; //ˮ�ʴ���
IWDG_HandleTypeDef hiwdg;
// TIM_HandleTypeDef htim1;

DMA_HandleTypeDef hdma_usart3_rx;
DMA_HandleTypeDef hdma_usart3_tx;
DMA_HandleTypeDef hdma_usart2_rx;
DMA_HandleTypeDef hdma_usart2_tx;

USART_RECEIVETYPE UsartTypeWiFi;
USART_RECEIVETYPE UsartTypeTOC;

struct rt_semaphore adc_cov_sem;
static struct rt_semaphore wq_comm_sem;
static struct rt_semaphore wifi_comm_sem;



extern rt_uint8_t WM_WorkMode;
// rt_int32_t time_update = 0;

/*func*/

extern int wifi_thread_init(void);
extern int Timer_init(void);
extern int flex_button_main(void);
extern int WVL_init(void);
extern void WVL_VolumCount(uint16_t GPIO_Pin);
extern int TOC_init(void);

/*action 
0 led_off 
1 led on
*/
void ctrl_led(led_enum led, int action)
{
    GPIO_PinState state;

   //    LOG_I("LED start %d, %d\n",led,action);

    if (action == LED_ON)
        state = GPIO_PIN_RESET;
    else
        state = GPIO_PIN_SET;
    switch (led)
    {
    case LED_SYS:
        HAL_GPIO_WritePin(LED_SYS_GPIO_Port, LED_SYS_Pin, state);
        break;
    case LED_SIG:
        HAL_GPIO_WritePin(LED_SIG_GPIO_Port, LED_SIG_Pin, state);
        break;
    case LED_TEST:
        HAL_GPIO_WritePin(LED_TEST_GPIO_Port, LED_TEST_Pin, state);
        break;
    case LED_WATER:
        HAL_GPIO_WritePin(LED_WATER_GPIO_Port, LED_WATER_Pin, state);
        break;
    case LED_FAULT:
        HAL_GPIO_WritePin(LED_FAULT_GPIO_Port, LED_FAULT_Pin, state);
        break;
    case LED_TDS:
        HAL_GPIO_WritePin(LED_TDS_GPIO_Port, LED_TDS_Pin, state);
        break;
    case LED_TOC:
        HAL_GPIO_WritePin(LED_TOC_GPIO_Port, LED_TOC_Pin, state);
        break;
    default:
        break;
    }
}

rt_err_t WTT_GetValue(uint32_t * pValue, uint32_t lenth)
{
	rt_err_t result;
	
        HAL_ADC_Start_DMA(&hadc1, pValue, lenth);
        result = rt_sem_take(&adc_cov_sem, 1000);

	return result;
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	WVL_VolumCount(GPIO_Pin);
}
#if 0
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if(htim->Instance == htim1.Instance)
    {
        time_update = 1;

    }
}
/**
  * @brief This function handles TIM1 update interrupt.
  */
void TIM1_UP_IRQHandler(void)
{
  /* USER CODE BEGIN TIM1_UP_IRQn 0 */

  /* USER CODE END TIM1_UP_IRQn 0 */
  HAL_TIM_IRQHandler(&htim1);
  /* USER CODE BEGIN TIM1_UP_IRQn 1 */

  /* USER CODE END TIM1_UP_IRQn 1 */
}
#endif
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
    HAL_ADC_Stop_DMA(&hadc1);
    rt_sem_release(&adc_cov_sem);
}

void startIWDG(void)
{
   __HAL_IWDG_START(&hiwdg);
}
void clearIWDG(void)
{
   HAL_IWDG_Refresh(&hiwdg);
}

void ADC1_2_IRQHandler(void)
{
    /* USER CODE BEGIN ADC1_2_IRQn 0 */

    /* USER CODE END ADC1_2_IRQn 0 */
    HAL_ADC_IRQHandler(&hadc1);
    /* USER CODE BEGIN ADC1_2_IRQn 1 */

    /* USER CODE END ADC1_2_IRQn 1 */
}
void EXTI15_10_IRQHandler(void)
{
    /* USER CODE BEGIN EXTI15_10_IRQn 0 */

    /* USER CODE END EXTI15_10_IRQn 0 */
    HAL_GPIO_EXTI_IRQHandler(TRG2_Pin);
    HAL_GPIO_EXTI_IRQHandler(TRG1_Pin);
    /* USER CODE BEGIN EXTI15_10_IRQn 1 */

    /* USER CODE END EXTI15_10_IRQn 1 */
}
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

    /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
    RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
    /** Initializes the CPU, AHB and APB buses clocks
  */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV8;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
    {
        Error_Handler();
    }
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
    PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV8;
    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
    {
        Error_Handler();
    }
}
void HAL_MspInit(void)
{
  /* USER CODE BEGIN MspInit 0 */

  /* USER CODE END MspInit 0 */

  __HAL_RCC_AFIO_CLK_ENABLE();
  __HAL_RCC_PWR_CLK_ENABLE();

  /* System interrupt init*/

  /** NOJTAG: JTAG-DP Disabled and SW-DP Enabled
  */
  __HAL_AFIO_REMAP_SWJ_NOJTAG();

  /* USER CODE BEGIN MspInit 1 */

  /* USER CODE END MspInit 1 */
}
void DMA1_Channel1_IRQHandler(void)
{
    /* USER CODE BEGIN DMA1_Channel1_IRQn 0 */

    /* USER CODE END DMA1_Channel1_IRQn 0 */
    HAL_DMA_IRQHandler(&hdma_adc1);
    /* USER CODE BEGIN DMA1_Channel1_IRQn 1 */

    /* USER CODE END DMA1_Channel1_IRQn 1 */
}
static void MX_IWDG_Init(void)
{

  /* USER CODE BEGIN IWDG_Init 0 */

  /* USER CODE END IWDG_Init 0 */

  /* USER CODE BEGIN IWDG_Init 1 */

  /* USER CODE END IWDG_Init 1 */
  hiwdg.Instance = IWDG;
  hiwdg.Init.Prescaler = IWDG_PRESCALER_64;
  hiwdg.Init.Reload = 1250;
  if (HAL_IWDG_Init(&hiwdg) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN IWDG_Init 2 */

  /* USER CODE END IWDG_Init 2 */

}
#if 0
/**
* @brief TIM_Base MSP Initialization
* This function configures the hardware resources used in this example
* @param htim_base: TIM_Base handle pointer
* @retval None
*/
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base)
{
  if(htim_base->Instance==TIM1)
  {
  /* USER CODE BEGIN TIM1_MspInit 0 */

  /* USER CODE END TIM1_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_TIM1_CLK_ENABLE();
    /* TIM1 interrupt Init */
    HAL_NVIC_SetPriority(TIM1_UP_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(TIM1_UP_IRQn);
  /* USER CODE BEGIN TIM1_MspInit 1 */

  /* USER CODE END TIM1_MspInit 1 */
  }

}

/**
* @brief TIM_Base MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param htim_base: TIM_Base handle pointer
* @retval None
*/
void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* htim_base)
{
  if(htim_base->Instance==TIM1)
  {
  /* USER CODE BEGIN TIM1_MspDeInit 0 */

  /* USER CODE END TIM1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_TIM1_CLK_DISABLE();

    /* TIM1 interrupt DeInit */
    HAL_NVIC_DisableIRQ(TIM1_UP_IRQn);
  /* USER CODE BEGIN TIM1_MspDeInit 1 */

  /* USER CODE END TIM1_MspDeInit 1 */
  }

}
#endif
void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(hadc->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspInit 0 */

  /* USER CODE END ADC1_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_ADC1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**ADC1 GPIO Configuration
    PA0-WKUP     ------> ADC1_IN0
    PA1     ------> ADC1_IN1
    PA4     ------> ADC1_IN4
    PA5     ------> ADC1_IN5
    PA6     ------> ADC1_IN6
    */
    GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5
                          |GPIO_PIN_6;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USER CODE BEGIN ADC1_MspInit 1 */

  /* USER CODE END ADC1_MspInit 1 */
  }

}

/**
* @brief ADC MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hadc: ADC handle pointer
* @retval None
*/
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
{
  if(hadc->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspDeInit 0 */

  /* USER CODE END ADC1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_ADC1_CLK_DISABLE();

    /**ADC1 GPIO Configuration
    PA0-WKUP     ------> ADC1_IN0
    PA1     ------> ADC1_IN1
    PA4     ------> ADC1_IN4
    PA5     ------> ADC1_IN5
    PA6     ------> ADC1_IN6
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5
                          |GPIO_PIN_6);

  /* USER CODE BEGIN ADC1_MspDeInit 1 */

  /* USER CODE END ADC1_MspDeInit 1 */
  }

}
#if 0
/**
  * @brief TIM1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM1_Init(void)
{

  /* USER CODE BEGIN TIM1_Init 0 */

  /* USER CODE END TIM1_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM1_Init 1 */

  /* USER CODE END TIM1_Init 1 */
  htim1.Instance = TIM1;
  htim1.Init.Prescaler = 64000-1;
  htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim1.Init.Period = 1001;
  htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim1.Init.RepetitionCounter = 0;
  htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim1) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM1_Init 2 */

  /* USER CODE END TIM1_Init 2 */

}
#endif
static void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */
  /** Common config
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOC, ES0_Pin|LED_TOC_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, LED_WATER_Pin|LED_TDS_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, LED_TEST_Pin|LED_SIG_Pin|LED_SYS_Pin|VALUE2_Pin
                          |VALUE1_Pin|LED_FAULT_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : KEY_Pin */
  GPIO_InitStruct.Pin = KEY_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(KEY_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : ES0_Pin LED_TOC_Pin */
  GPIO_InitStruct.Pin = ES0_Pin|LED_TOC_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

  /*Configure GPIO pins : LED_WATER_Pin LED_TDS_Pin */
  GPIO_InitStruct.Pin = LED_WATER_Pin|LED_TDS_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : LED_TEST_Pin LED_SIG_Pin LED_SYS_Pin VALUE2_Pin
                           VALUE1_Pin LED_FAULT_Pin */
  GPIO_InitStruct.Pin = LED_TEST_Pin|LED_SIG_Pin|LED_SYS_Pin|VALUE2_Pin
                          |VALUE1_Pin|LED_FAULT_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : TRG2_Pin TRG1_Pin */
  GPIO_InitStruct.Pin = TRG2_Pin|TRG1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* EXTI interrupt init*/
  HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);

}
// static void MX_GPIO_Init(void)
// {
//     GPIO_InitTypeDef GPIO_InitStruct = {0};

//     /* GPIO Ports Clock Enable */
//     __HAL_RCC_GPIOC_CLK_ENABLE();
//     __HAL_RCC_GPIOA_CLK_ENABLE();
//     __HAL_RCC_GPIOB_CLK_ENABLE();

//     /*Configure GPIO pin Output Level */
//     HAL_GPIO_WritePin(LED_TOC_GPIO_Port, LED_TOC_Pin, GPIO_PIN_RESET);

//     /*Configure GPIO pin Output Level */
//     HAL_GPIO_WritePin(GPIOA, LED_TDS_Pin |LED_WATER_Pin, GPIO_PIN_RESET);

//     /*Configure GPIO pin Output Level */
//     HAL_GPIO_WritePin(GPIOB, LED_FAULT_Pin | LED_TEST_Pin | LED_SIG_Pin | LED_SYS_Pin | VALUE2_Pin | VALUE1_Pin, GPIO_PIN_RESET);

//     /*Configure GPIO pin : KEY_Pin */
//     GPIO_InitStruct.Pin = KEY_Pin;
//     GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
//     GPIO_InitStruct.Pull = GPIO_PULLUP;
//     HAL_GPIO_Init(KEY_GPIO_Port, &GPIO_InitStruct);

//     /*Configure GPIO pin : LED_TOC_Pin */
//     GPIO_InitStruct.Pin = LED_TOC_Pin;
//     GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
//     GPIO_InitStruct.Pull = GPIO_PULLUP;
//     GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
//     HAL_GPIO_Init(LED_TOC_GPIO_Port, &GPIO_InitStruct);

//     /*Configure GPIO pins : LED_TOC_Pin LED_WATER_Pin */
//     GPIO_InitStruct.Pin = LED_TDS_Pin | LED_WATER_Pin;
//     GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
//     GPIO_InitStruct.Pull = GPIO_PULLUP;
//     GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
//     HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

//     /*Configure GPIO pins : LED_TEST_Pin LED_SIG_Pin LED_SYS_Pin VALUE2_Pin
//                            VALUE1_Pin */
//     GPIO_InitStruct.Pin = LED_TEST_Pin | LED_SIG_Pin | LED_SYS_Pin | VALUE2_Pin | VALUE1_Pin | LED_FAULT_Pin;
//     GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
//     GPIO_InitStruct.Pull = GPIO_PULLUP;
//     GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
//     HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

//     /*Configure GPIO pin : PA12 */
//     GPIO_InitStruct.Pin = GPIO_PIN_12;
//     GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
//     GPIO_InitStruct.Pull = GPIO_PULLUP;
//     HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

// 	/*Configure GPIO pin : GPIO_PIN_14  wifi ES0 ����*/
// 	GPIO_InitStruct.Pin = GPIO_PIN_14;    
// 	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;    
// 	GPIO_InitStruct.Pull = GPIO_PULLUP;    
// 	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;    
// 	HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
// 	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_14, GPIO_PIN_SET);

	
//     /* EXTI interrupt init*/
//     HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
//     HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
// }

void set_AT_mode(void)
{ 

	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_14, GPIO_PIN_RESET); 
	rt_thread_mdelay(800); 
	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_14, GPIO_PIN_SET);
	rt_thread_mdelay(500); 

}
static void MX_DMA_Init(void)
{

    /* DMA controller clock enable */
    __HAL_RCC_DMA1_CLK_ENABLE();

    /* DMA interrupt init */
    /* DMA1_Channel1_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
    /* DMA1_Channel2_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Channel2_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel2_IRQn);
    /* DMA1_Channel3_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Channel3_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel3_IRQn);
    /* DMA1_Channel4_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Channel4_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel4_IRQn);
    /* DMA1_Channel6_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn);
    /* DMA1_Channel7_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Channel7_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Channel7_IRQn);
}


/********* ���ں��� **********/
void DMA1_Channel2_IRQHandler(void)
{
    /* USER CODE BEGIN DMA1_Channel2_IRQn 0 */

    /* USER CODE END DMA1_Channel2_IRQn 0 */
    HAL_DMA_IRQHandler(&hdma_usart3_tx);
    /* USER CODE BEGIN DMA1_Channel2_IRQn 1 */

    /* USER CODE END DMA1_Channel2_IRQn 1 */
}
void DMA1_Channel3_IRQHandler(void)
{
    /* USER CODE BEGIN DMA1_Channel3_IRQn 0 */

    /* USER CODE END DMA1_Channel3_IRQn 0 */
    HAL_DMA_IRQHandler(&hdma_usart3_rx);
    /* USER CODE BEGIN DMA1_Channel3_IRQn 1 */

    /* USER CODE END DMA1_Channel3_IRQn 1 */
}

void DMA1_Channel6_IRQHandler(void)
{    
	/* USER CODE BEGIN DMA1_Channel6_IRQn 0 */    
	/* USER CODE END DMA1_Channel6_IRQn 0 */    
	HAL_DMA_IRQHandler(&hdma_usart2_rx);    
	/* USER CODE BEGIN DMA1_Channel6_IRQn 1 */    
	/* USER CODE END DMA1_Channel6_IRQn 1 */
}

void DMA1_Channel7_IRQHandler(void)
{    
	/* USER CODE BEGIN DMA1_Channel7_IRQn 0 */    
	/* USER CODE END DMA1_Channel7_IRQn 0 */    
	HAL_DMA_IRQHandler(&hdma_usart2_tx);    
	/* USER CODE BEGIN DMA1_Channel7_IRQn 1 */   
	/* USER CODE END DMA1_Channel7_IRQn 1 */
}

#if 0

rt_uint8_t * Uart_GetTocData(rt_uint16_t *Size)
{
	*Size = UsartTypeTOC.rx_len;
	return UsartTypeTOC.usartDMA_rxBuf;
}

rt_uint8_t * Uart_GetWiFiData(rt_uint16_t *Size)
{
	*Size = UsartTypeWiFi.rx_len;
	return UsartTypeWiFi.usartDMA_rxBuf;
}
void UsartReceive_IDLE(UART_HandleTypeDef *huart, USART_RECEIVETYPE *UsartType)
{
    uint32_t temp;
    if ((__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) != RESET))
    {
        __HAL_UART_CLEAR_IDLEFLAG(huart);
        HAL_UART_DMAStop(huart);
        temp = huart->hdmarx->Instance->CNDTR;
        UsartType->rx_len = RECEIVELEN - temp;
        if (UsartType->rx_len == 0x400)
            UsartType->receive_flag = 1;              //�յ�����
            
        HAL_UART_Receive_DMA(huart, UsartType->usartDMA_rxBuf, RECEIVELEN); //��DMA�յ����ݷŵ�UsartType1.usartDMA_rxBuf
        if (huart == &huart3) //ˮ�ʴ���
        {
            rt_sem_release(&wq_comm_sem);
            rt_kprintf("uart3 get len %d \n",UsartType->rx_len);
        }
        else if(huart == &huart2) //wifi ����
        {
        	        //�������ݵ�ָ��buf
       		 //InsCopy(UsartType1.usartDMA_rxBuf,ins_struct.insp_end,UsartType1.rx_len);

            rt_sem_release(&wifi_comm_sem);
        }
    }
}


WIFI_SendMessage
#endif

rt_uint8_t AtCheck[4];  // 0x6f,0x6b,0xd,0xa ��4��������ʾok


void UsartReceive_IDLE(UART_HandleTypeDef *huart, USART_RECEIVETYPE *UsartType)
{
    uint32_t temp;

	
    if ((__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) != RESET))
    {
        __HAL_UART_CLEAR_IDLEFLAG(huart);
        HAL_UART_DMAStop(huart);
        temp = huart->hdmarx->Instance->CNDTR;
        UsartType->rx_len = RECEIVELEN - temp;

        HAL_UART_Receive_DMA(huart, UsartType->usartDMA_rxBuf, RECEIVELEN); //��DMA�յ����ݷŵ�UsartType1.usartDMA_rxBuf
        
        if (huart == &huart3) //ˮ�ʴ���
        {
        	if(UsartType->rx_len > 1)
			{
	            rt_sem_release(&wq_comm_sem);
//	            rt_kprintf("uart3 get len %d \n",UsartType->rx_len);
			}
        }
        else if(huart == &huart2) //wifi ����
        {
        	        //�������ݵ�ָ��buf
       		 //InsCopy(UsartType1.usartDMA_rxBuf,ins_struct.insp_end,UsartType1.rx_len);

//#if 0
    		if (WM_WorkMode != WIFI_DATA_MODE)
			{
				rt_uint16_t idx;

/*

				if(AtCmdPktLen<4)
				{
					idx=0;
				}
				else
				{
					idx = AtCmdPktLen;
				}

				pData = &UsartType->usartDMA_rxBuf[idx];

				HAL_UART_Receive_DMA(huart, pData, RECEIVELEN); //��DMA�յ����ݷŵ�UsartType1.usartDMA_rxBuf
				AtCmdPktLen += UsartType->rx_len;
				
				rt_kprintf("uart 2 get len = %d, idx = %d pktLen = %d\n",UsartType->rx_len,idx,AtCmdPktLen);

					for(int i=0;i<AtCmdPktLen;i++)
					{
			            rt_kprintf(" %x ",UsartType->usartDMA_rxBuf[i]);
					}
					rt_kprintf("\n");

				
				if(AtCmdPktLen >= 4)
				{
					pData=&UsartType->usartDMA_rxBuf[AtCmdPktLen-4];

				}

				
				if((pData[0] != 0x20 && pData[1] != 0x0d &&   pData[2] == 0x0d && pData[3] == 0x0a) || pData[3] == 0)
				{
					AtCmdPktLen = 0;
					rt_sem_release(&wifi_comm_sem);
				}
*/

//		        HAL_UART_Receive_DMA(huart, UsartType->usartDMA_rxBuf, RECEIVELEN); //��DMA�յ����ݷŵ�UsartType1.usartDMA_rxBuf
				rt_kprintf("uart2 get len %d :\n",UsartType->rx_len);
/*				for(int i=0;i<UsartType->rx_len;i++)
				{
					rt_kprintf(" %x",UsartType->usartDMA_rxBuf[i]);
				}
				rt_kprintf("\n");

*/	
				if(UsartType->rx_len<4)
				{
					idx=4-UsartType->rx_len;
					for(int i=0;i<idx;i++)
					{
						AtCheck[i] = AtCheck[i+UsartType->rx_len];
					}
					for(int i=0;i<UsartType->rx_len;i++)
					{
						AtCheck[i+idx] = UsartType->usartDMA_rxBuf[i];
					}
				}
				else
				{
					for(int i=0;i<4;i++)
					{
						AtCheck[i] = UsartType->usartDMA_rxBuf[UsartType->rx_len-4+i];
					}
				}

				if(AtCheck[0] != 0x20 && AtCheck[1] != 0x0d && AtCheck[2] == 0x0d && AtCheck[3] == 0x0a)
				{
					rt_sem_release(&wifi_comm_sem);
				}
				
			}
			else
			{
				WIFI_SendMessage(WIFI_MSG_TYPE);
			}
//#endif	
        }
    }
}

void USART2_IRQHandler(void) // wifi �����ж�
{
    /* USER CODE BEGIN USART2_IRQn 0 */
    UsartReceive_IDLE(&huart2, &UsartTypeWiFi);
    /* USER CODE END USART2_IRQn 0 */
    HAL_UART_IRQHandler(&huart2);
    /* USER CODE BEGIN USART2_IRQn 1 */

    /* USER CODE END USART2_IRQn 1 */
}
void USART3_IRQHandler(void)// ˮ�� �����ж�
{
    /* USER CODE BEGIN USART3_IRQn 0 */
    UsartReceive_IDLE(&huart3, &UsartTypeTOC);
    /* USER CODE END USART3_IRQn 0 */
    HAL_UART_IRQHandler(&huart3);
    /* USER CODE BEGIN USART3_IRQn 1 */

    /* USER CODE END USART3_IRQn 1 */
}

void HAL_UART_MspDeInit(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART2)
    {
        /* USER CODE BEGIN USART2_MspDeInit 0 */

        /* USER CODE END USART2_MspDeInit 0 */
        /* Peripheral clock disable */
        __HAL_RCC_USART2_CLK_DISABLE();

        /**USART2 GPIO Configuration
    PA2     ------> USART2_TX
    PA3     ------> USART2_RX
    */
        HAL_GPIO_DeInit(GPIOA, COM_TX_Pin | COM_RX_Pin);

        /* USART2 DMA DeInit */
        HAL_DMA_DeInit(huart->hdmarx);
        HAL_DMA_DeInit(huart->hdmatx);

        /* USART2 interrupt DeInit */
        HAL_NVIC_DisableIRQ(USART2_IRQn);
        /* USER CODE BEGIN USART2_MspDeInit 1 */

        /* USER CODE END USART2_MspDeInit 1 */
    }
    else if (huart->Instance == USART3)
    {
        /* USER CODE BEGIN USART3_MspDeInit 0 */

        /* USER CODE END USART3_MspDeInit 0 */
        /* Peripheral clock disable */
        __HAL_RCC_USART3_CLK_DISABLE();

        /**USART3 GPIO Configuration
    PB10     ------> USART3_TX
    PB11     ------> USART3_RX
    */
        HAL_GPIO_DeInit(GPIOB, WAT_TX_Pin | WAT_RX_Pin);

        /* USART3 DMA DeInit */
        HAL_DMA_DeInit(huart->hdmarx);
        HAL_DMA_DeInit(huart->hdmatx);

        /* USART3 interrupt DeInit */
        HAL_NVIC_DisableIRQ(USART3_IRQn);
        /* USER CODE BEGIN USART3_MspDeInit 1 */

        /* USER CODE END USART3_MspDeInit 1 */
    }
}
static void MX_USART3_UART_Init(void)
{

    /* USER CODE BEGIN USART3_Init 0 */

    /* USER CODE END USART3_Init 0 */

    /* USER CODE BEGIN USART3_Init 1 */

    /* USER CODE END USART3_Init 1 */
    huart3.Instance = USART3;
    huart3.Init.BaudRate = 9600;
    huart3.Init.WordLength = UART_WORDLENGTH_8B;
    huart3.Init.StopBits = UART_STOPBITS_2;
    huart3.Init.Parity = UART_PARITY_NONE;
    huart3.Init.Mode = UART_MODE_TX_RX;
    huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart3.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart3) != HAL_OK)
    {
        Error_Handler();
    }
    /* USER CODE BEGIN USART3_Init 2 */

    /* USER CODE END USART3_Init 2 */
}
static void MX_USART2_UART_Init(void)
{

    /* USER CODE BEGIN USART2_Init 0 */

    /* USER CODE END USART2_Init 0 */

    /* USER CODE BEGIN USART2_Init 1 */

    /* USER CODE END USART2_Init 1 */
    huart2.Instance = USART2;
    huart2.Init.BaudRate = 115200;
    huart2.Init.WordLength = UART_WORDLENGTH_8B;
    huart2.Init.StopBits = UART_STOPBITS_1;
    huart2.Init.Parity = UART_PARITY_NONE;
    huart2.Init.Mode = UART_MODE_TX_RX;
    huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart2.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart2) != HAL_OK)
    {
        Error_Handler();
    }
    /* USER CODE BEGIN USART2_Init 2 */

    /* USER CODE END USART2_Init 2 */
}
void SendDataUSART_DMA(UART_HandleTypeDef *huart, rt_uint8_t *pData, rt_uint16_t Size)
{
    while (HAL_DMA_GetState(huart->hdmatx) == HAL_DMA_STATE_BUSY)
        rt_thread_mdelay(1);
    HAL_UART_Transmit_DMA(huart, pData, Size);
}


rt_err_t WTOC_SendDate(rt_uint8_t *pData, rt_uint16_t Size)
{
    rt_err_t result = RT_EOK;

	rt_memset(UsartTypeTOC.usartDMA_rxBuf,0,RECEIVELEN);

//	rt_kprintf("send len %d\n",Size);
	
    SendDataUSART_DMA(&huart3, pData, Size);
    result = rt_sem_take(&wq_comm_sem, 3000);
    if(result != RT_EOK)
    {
//		rt_kprintf("TOC uart send erro, code %d\n", result);
    }

    rt_thread_delay(500);

    return result;

}

rt_uint8_t * WTOC_GetDate(rt_uint16_t * len)
{
	*len = UsartTypeTOC.rx_len;
	return &UsartTypeTOC.usartDMA_rxBuf[7];

}

rt_err_t Wifi_SendDate(rt_uint8_t *pData, rt_uint16_t Size)
{
    rt_err_t result = RT_EOK;

	rt_memset(UsartTypeWiFi.usartDMA_rxBuf,0,RECEIVELEN);
    SendDataUSART_DMA(&huart2, pData, Size);

	rt_kprintf("wifi send len %d -->\n ",Size);
	rt_kprintf("%s ",(char *)pData);

//   	rt_memset(pData,0,Size+1);

/*
	for(int i=0;i<Size;i++)
	{
	rt_kprintf("%x ",pData[i]);
	}
	rt_kprintf("\n");
*/	

	if (WM_WorkMode != WIFI_DATA_MODE)
	{
//		rt_thread_delay(500);
		result = rt_sem_take(&wifi_comm_sem, 2000);
	    if(result != RT_EOK)
	    {
			rt_kprintf("wifi uart send erro, code %d\n", result);
	    }

    }
    else
    {
		rt_thread_delay(1000);
    }

    return result;

}

rt_uint8_t * Wifi_GetDate(rt_uint16_t * len)
{
	*len = UsartTypeWiFi.rx_len;
	return &UsartTypeWiFi.usartDMA_rxBuf[0];

}



/********* end of ���ں��� **********/


void init_wq_board()
{

	MX_GPIO_Init();
	MX_DMA_Init();
	MX_USART2_UART_Init();
	MX_USART3_UART_Init();
	MX_ADC1_Init();
//    MX_TIM1_Init();
	HAL_UART_Receive_DMA(&huart2, UsartTypeWiFi.usartDMA_rxBuf, RECEIVELEN);
	HAL_UART_Receive_DMA(&huart3, UsartTypeTOC.usartDMA_rxBuf, RECEIVELEN);
	__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE);
	__HAL_UART_ENABLE_IT(&huart3, UART_IT_IDLE);

    UsartTypeWiFi.dmaSend_flag = USART_DMA_SENDOVER;
    UsartTypeTOC.dmaSend_flag = USART_DMA_SENDOVER;
    HAL_NVIC_DisableIRQ(DMA1_Channel1_IRQn);


    MX_IWDG_Init();
    
}


uint16_t ADC_Read(uint32_t Channel)
{
    uint16_t value;
    ADC_ChannelConfTypeDef sConfig = {
    0};
    sConfig.Channel = Channel;                                         /* 通道 */
    sConfig.Rank = ADC_REGULAR_RANK_1;
    sConfig.SamplingTime = ADC_SAMPLETIME_55CYCLES_5;                  /* 采样时间 */
    if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
    {

        Error_Handler();
    }
    HAL_ADC_Start(&hadc1);
    HAL_ADC_PollForConversion(&hadc1, HAL_MAX_DELAY);
    value = (uint16_t)HAL_ADC_GetValue(&hadc1);
    HAL_ADC_Stop(&hadc1);
    return value;
}
int main(void)
{
    int i;

    LOG_D("Hello RT-Thread!");

    rt_sem_init(&adc_cov_sem, "adc_cov", 0, RT_IPC_FLAG_PRIO);
    rt_sem_init(&wq_comm_sem, "wq_comm", 0, RT_IPC_FLAG_PRIO);
    rt_sem_init(&wifi_comm_sem, "wifi_comm", 0, RT_IPC_FLAG_PRIO);

        init_wq_board();

    for (i = 0; i < LED_MAX; i++)
    {
        ctrl_led(i, LED_OFF);
    }
 /*   
    rt_thread_init(&adc_thread, "adc_thread", adc_thread_entry,
                   RT_NULL, &adc_thread_stack[0], sizeof(adc_thread_stack),
                   ADC_THREAD_PRIORITY, ADC_THREAD_TIMESLICE);
    rt_thread_startup(&adc_thread);
*/


    wifi_thread_init();
	TOC_init();
    flex_button_main();
	WVL_init();
    Timer_init();

//    HAL_TIM_Base_Start_IT(&htim1);
    startIWDG();
    while (1)
    {
/*        if(time_update == 1)
        {
            rt_kprintf("tim1 update");
            time_update = 0;
        }
*/      rt_thread_mdelay(1000);
      clearIWDG();

    }
    return RT_EOK;

}

